package com.yeskery.nut.web.demo.controller;

import com.yeskery.nut.annotation.api.Api;
import com.yeskery.nut.annotation.api.ApiGroup;
import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.web.PostMapping;
import com.yeskery.nut.annotation.web.RequestBody;
import com.yeskery.nut.annotation.web.RequestMapping;
import com.yeskery.nut.annotation.web.RestController;
import com.yeskery.nut.extend.i18n.MessageService;
import com.yeskery.nut.util.StringUtils;
import com.yeskery.nut.web.demo.biz.AuthBiz;
import com.yeskery.nut.web.demo.common.Auth;
import com.yeskery.nut.web.demo.common.R;
import com.yeskery.nut.web.demo.dto.UserLoginDto;
import com.yeskery.nut.web.demo.dto.UserRegisterDto;
import jakarta.validation.Valid;

/**
 * 用户认证controller
 * @author Yeskery
 * 2023/7/28
 */
@ApiGroup("用户认证")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthBiz authBiz;

    @Autowired
    private MessageService messageService;

    /**
     * 登录
     * @param dto
     * @return
     */
    @Api("登录")
    @Auth(required = false)
    @PostMapping("/login")
    public R<?> login(@Valid @RequestBody UserLoginDto dto) {
        String token = authBiz.login(dto.getUsername(), dto.getPassword());
        return StringUtils.isEmpty(token) ? R.fail(messageService.getMessage("auth.fail")) : R.ok(token);
    }

    /**
     * 注册
     * @param dto
     * @return
     */
    @Api("注册")
    @Auth(required = false)
    @PostMapping("/register")
    public R<?> register(@Valid @RequestBody UserRegisterDto dto) {
        authBiz.register(dto.getUsername(), dto.getPassword(), dto.getNickname());
        return R.ok(null, messageService.getMessage("auth.ok"));
    }
}
